package tabdulin.sms.visual;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Rectangle;
import java.io.IOException;
import java.net.MalformedURLException;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import org.apache.log4j.Logger;

import tabdulin.sms.InvalidSmsException;
import tabdulin.sms.Operator;
import tabdulin.sms.Sms;
import tabdulin.sms.megafon.MegafonOperator;
import tabdulin.sms.megafon.MegafonStatus;

/**
 * @author Talgat Abdulin
 *
 */
@SuppressWarnings("serial")
public class SmsSenderFrame extends JFrame {
    private final static Logger logger = Logger.getLogger(SmsSenderFrame.class);
    
    private JPanel jContentPane = null; 
    private JLabel operatorSelectLabel = null;
    private JComboBox operatorsComboBox = null;
    private JComboBox prefixComboBox = null;
    private JTextField numberTextField = null;
    private JTextArea messageTextArea = null;
    private JLabel captchaImageLabel = null;
    private JLabel fromLabel = null;
    private JTextField senderTextField = null;
    private JTextField captchaCodeTextField = null;
    private JLabel enterCodeLabel = null;
    private JButton sendButton = null;
    private JButton closeButton = null;
    private JCheckBox translitCheckBox = null;
    private JLabel translitLabel = null;
    private JLabel messageLengthLabel = null;
    private JLabel statusBarLabel = null;

    private JMenuBar menuBar = null;
    private JMenu mainMenu = null;
    private JMenu contactsMenu = null;
    private JMenu helpMenu = null;
    private JMenuItem newSmsMenuItem = null;
    private JMenuItem saveContactMenuItem = null;
    private JMenuItem contactListMenuItem = null;
    private JMenuItem helpMenuItem = null;
    private JMenuItem aboutMenuItem = null;
    
    private Operator operator;
    
    /**
     * This is the default constructor
     */
    public SmsSenderFrame() {
        super();
        try {
            operator = new MegafonOperator();
        } catch (IOException e) {
            // TODO : 
            logger.error(e);
        }
        initialize();
    }

    /**
     * This method initializes this
     * 
     * @return void
     */
    private void initialize() {
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);
        this.setFont(new Font("UnDotum", Font.PLAIN, 14));
        this.setBounds(new Rectangle(200, 100, 254, 350));
        this.setTitle("SMS Sender");
        this.setContentPane(getJContentPane());
        this.setJMenuBar(getAppMenuBar());
        this.addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent e) {
                operator.closeSession();
            }
        });
    }

    /**
     * This method initializes jContentPane
     * 
     * @return javax.swing.JPanel
     */
    private JPanel getJContentPane() {
        if (jContentPane == null) {
            translitLabel = new JLabel();
            translitLabel.setBounds(new Rectangle(28, 174, 60, 20));
            translitLabel.setFont(new Font("UnDotum", Font.BOLD, 12));
            translitLabel.setText("Транслит");
            enterCodeLabel = new JLabel();
            enterCodeLabel.setBounds(new Rectangle(124, 198, 114, 20));
            enterCodeLabel.setHorizontalAlignment(SwingConstants.CENTER);
            enterCodeLabel.setFont(new Font("UnDotum", Font.BOLD, 12));
            enterCodeLabel.setText("Введите код");
            fromLabel = new JLabel();
            fromLabel.setBounds(new Rectangle(4, 56, 60, 20));
            fromLabel.setHorizontalAlignment(SwingConstants.CENTER);
            fromLabel.setFont(new Font("UnDotum", Font.BOLD, 12));
            fromLabel.setText("От: ");
            captchaImageLabel = new JLabel();
            captchaImageLabel.setBounds(new Rectangle(4, 197, 113, 50));
            captchaImageLabel.setText("");
            jContentPane = new JPanel();
            jContentPane.setLayout(null);
            jContentPane.setSize(new Dimension(243, 424));
            jContentPane.add(getOperatorSelectLabel(), null);
            jContentPane.add(getOperatorsComboBox(), null);
            jContentPane.add(getPrefixComboBox(), null);
            jContentPane.add(getNumberTextField(), null);
            jContentPane.add(captchaImageLabel, null);
            jContentPane.add(fromLabel, null);
            jContentPane.add(getSenderTextField(), null);
            jContentPane.add(getCaptchaCodeTextField(), null);
            jContentPane.add(enterCodeLabel, null);
            jContentPane.add(getSendButton(), null);
            jContentPane.add(getCloseButton(), null);
            jContentPane.add(getTranslitCheckBox(), null);
            jContentPane.add(translitLabel, null);
            jContentPane.add(getMessageLengthLabel(), null);
            jContentPane.add(getStatusBarLabel(), null);
            jContentPane.add(getMessageTextArea(), null);
        }
        return jContentPane;
    }

    /**
     * This method initializes operatorSelectLabel
     * 
     * @return javax.swing.JLabel
     */
    public JLabel getOperatorSelectLabel() {
        if (operatorSelectLabel == null) {
            operatorSelectLabel = new JLabel();
            operatorSelectLabel.setText("Оператор");
            operatorSelectLabel.setBounds(new Rectangle(4, 8, 60, 20));
            operatorSelectLabel.setFont(new Font("UnDotum", Font.BOLD, 12));
            operatorSelectLabel.setHorizontalAlignment(SwingConstants.CENTER);
            operatorSelectLabel.setBackground(Color.black);
        }
        return operatorSelectLabel;
    }

    /**
     * This method initializes operatorsComboBox
     * 
     * @return javax.swing.JComboBox
     */
    public JComboBox getOperatorsComboBox() {
        if (operatorsComboBox == null) {
            operatorsComboBox = new JComboBox();
            operatorsComboBox.setBounds(new Rectangle(70, 8, 168, 20));
            operatorsComboBox.setFont(new Font("UnDotum", Font.BOLD, 12));
            operatorsComboBox.addItem("Megafon Moscow");
        }
        return operatorsComboBox;
    }

    /**
     * This method initializes prefixComboBox
     * 
     * @return javax.swing.JComboBox
     */
    public JComboBox getPrefixComboBox() {
        if (prefixComboBox == null) {
            prefixComboBox = new JComboBox();
            prefixComboBox.setBounds(new Rectangle(4, 32, 60, 20));
            prefixComboBox.setFont(new Font("UnDotum", Font.BOLD, 12));
            prefixComboBox.addItem("925");
            prefixComboBox.addItem("926");
            prefixComboBox.addItem("495");
        }
        return prefixComboBox;
    }

    /**
     * This method initializes numberTextField
     * 
     * @return javax.swing.JTextField
     */
    private JTextField getNumberTextField() {
        if (numberTextField == null) {
            numberTextField = new JTextField();
            numberTextField.setBounds(new Rectangle(70, 32, 167, 21));
            numberTextField.setFont(new Font("UnDotum", Font.PLAIN, 12));
        }
        return numberTextField;
    }

    /**
     * This method initializes messageTextArea
     * 
     * @return javax.swing.JTextArea
     */
    private JTextArea getMessageTextArea() {
        if (messageTextArea == null) {
            messageTextArea = new JTextArea();
            messageTextArea.setLineWrap(true);
            messageTextArea.setTabSize(4);
            messageTextArea.setFont(new Font("UnDotum", Font.PLAIN, 12));
            messageTextArea.setBounds(new Rectangle(4, 80, 234, 88));
            messageTextArea.addKeyListener(new java.awt.event.KeyAdapter() {
                public void keyTyped(java.awt.event.KeyEvent e) {
                    getMessageLengthLabel().setText(getMessageLength(operator.getMaxMessageLength(isTranslitUsed())) + 
                            "/" + operator.getMaxMessageLength(isTranslitUsed()));
                }

            });
        }
        return messageTextArea;
    }

    /**
     * This method initializes sender
     * 
     * @return javax.swing.JTextField
     */
    private JTextField getSenderTextField() {
        if (senderTextField == null) {
            senderTextField = new JTextField();
            senderTextField.setBounds(new Rectangle(70, 56, 167, 20));
            senderTextField.setFont(new Font("UnDotum", Font.PLAIN, 12));
            senderTextField.addKeyListener(new java.awt.event.KeyAdapter() {
                public void keyTyped(java.awt.event.KeyEvent e) {
                    getMessageLengthLabel().setText(getMessageLength(operator.getMaxMessageLength(isTranslitUsed())) + "/" + operator.getMaxMessageLength(isTranslitUsed()));
                }
            });
        }
        return senderTextField;
    }

    /**
     * This method initializes captchaCodeTextField f
     * 
     * @return javax.swing.JTextField
     */
    private JTextField getCaptchaCodeTextField() {
        if (captchaCodeTextField == null) {
            captchaCodeTextField = new JTextField();
            captchaCodeTextField.setBounds(new Rectangle(124, 222, 114, 20));
            captchaCodeTextField.setFont(new Font("UnDotum", Font.PLAIN, 12));
        }
        return captchaCodeTextField;
    }

    /**
     * This method initializes sendButton
     * 
     * @return javax.swing.JButton
     */
    private JButton getSendButton() {
        if (sendButton == null) {
            sendButton = new JButton();
            sendButton.setBounds(new Rectangle(4, 251, 114, 20));
            sendButton.setText("Отправить");
            sendButton.setPreferredSize(new Dimension(60, 26));
            sendButton.setFont(new Font("UnDotum", Font.BOLD, 12));
            sendButton.setName("sendButton");
            sendButton.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent e) {
                    try {
                        Sms sms = new Sms();
                        sms.setSender(getSender());
                        sms.setPrefix(getPrefix());
                        sms.setNumber(getNumber());
                        sms.setMessage(getMessage());
                        sms.setCode(getCaptchaCodeTextField().getText().trim());
                        operator.validate(sms);
                        MegafonStatus status = new MegafonStatus(operator.send(sms));
                        setStatus(status.getMessage());
                    } catch (InvalidSmsException ise) {
                        setStatus(ise.getMessage());
                        logger.error(e);
                    } catch (IOException ioe) {
                        getStatusBarLabel().setText("Something weird happened");
                        logger.error(e);
                    }
                }
            });
        }
        return sendButton;
    }

    /**
     * This method initializes cancelButton
     * 
     * @return javax.swing.JButton
     */
    private JButton getCloseButton() {
        if (closeButton == null) {
            closeButton = new JButton();
            closeButton.setText("Закрыть");
            closeButton.setName("cancelButton");
            closeButton.setPreferredSize(new Dimension(60, 26));
            closeButton.setBounds(new Rectangle(124, 251, 114, 20));
            closeButton.setFont(new Font("UnDotum", Font.BOLD, 12));
            closeButton.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent e) {
                    operator.closeSession();
                    SmsSenderFrame.this.dispose();
                }
            });
        }
        return closeButton;
    }

    /**
     * This method initializes translitCheckBox
     * 
     * @return javax.swing.JCheckBox
     */
    private JCheckBox getTranslitCheckBox() {
        if (translitCheckBox == null) {
            translitCheckBox = new JCheckBox();
            translitCheckBox.setBounds(new Rectangle(4, 174, 17, 20));
            translitCheckBox.setSelected(true);
            return translitCheckBox;
        }
        return translitCheckBox;
    }
    
    /**
     * This method initializes messageLengthLabel
     * 
     * @return javax.swing.JLabel
     */
    private JLabel getMessageLengthLabel() {
        if (messageLengthLabel == null) {
            messageLengthLabel = new JLabel();
            messageLengthLabel.setHorizontalAlignment(SwingConstants.CENTER);
            messageLengthLabel.setFont(new Font("UnDotum", Font.BOLD, 12));
            messageLengthLabel.setBounds(new Rectangle(168, 174, 70, 20));
            messageLengthLabel.setText(operator.getMaxMessageLength(isTranslitUsed()) + "/" +
                    operator.getMaxMessageLength(isTranslitUsed()));
        }
        return messageLengthLabel;
    }

    /**
     * This method initializes statusBarLabel
     * 
     * @return javax.swing.JLabel
     */
    private JLabel getStatusBarLabel() {
        if (statusBarLabel == null) {
            statusBarLabel = new JLabel();
            statusBarLabel.setBounds(new Rectangle(5, 275, 234, 20));
            statusBarLabel.setFont(new Font("UnDotum", Font.PLAIN, 12));
        }
        return statusBarLabel;
    }
    
    private JMenuBar getAppMenuBar() {
        if (menuBar == null) {
            menuBar = new JMenuBar();
            menuBar.add(getMainMenu());
            menuBar.add(getContactsMenu());
            menuBar.add(getHelpMenu());
        }
        return menuBar;
    }

    /**
     * This method initializes mainMenu
     * 
     * @return javax.swing.JMenu
     */
    private JMenu getMainMenu() {
        if (mainMenu == null) {
            mainMenu = new JMenu();
            mainMenu.setText("СМС");
            mainMenu.setFont(new Font("UnDotum", Font.PLAIN, 12));
            mainMenu.add(getNewSmsMenuItem());
        }
        return mainMenu;
    }

    /**
     * This method initializes contactsMenu
     * 
     * @return javax.swing.JMenu
     */
    private JMenu getContactsMenu() {
        if (contactsMenu == null) {
            contactsMenu = new JMenu();
            contactsMenu.setText("Контакты");
            contactsMenu.setFont(new Font("UnDotum", Font.PLAIN, 12));
            contactsMenu.add(getSaveContactMenuItem());
            contactsMenu.add(getContactListMenuItem());
        }
        return contactsMenu;
    }

    /**
     * This method initializes helpMenu
     * 
     * @return javax.swing.JMenu
     */
    private JMenu getHelpMenu() {
        if (helpMenu == null) {
            helpMenu = new JMenu();
            helpMenu.setText("Помощь");
            helpMenu.setFont(new Font("UnDotum", Font.PLAIN, 12));
            helpMenu.add(getHelpMenuItem());
            helpMenu.add(getAboutMenuItem());
        }
        return helpMenu;
    }

    /**
     * This method initializes newSmsMenuItem
     * 
     * @return javax.swing.JMenuItem
     */
    private JMenuItem getNewSmsMenuItem() {
        if (newSmsMenuItem == null) {
            newSmsMenuItem = new JMenuItem();
            newSmsMenuItem.setText("Новое СМС");
            newSmsMenuItem.setFont(new Font("UnDotum", Font.PLAIN, 12));
            newSmsMenuItem.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    try {
                        operator.startSession();
                        SmsSenderFrame.this.setCaptchaImageLabel(operator.getCaptchaFileName());
                        setMessage(null);
                        setCaptchaCode(null);
                        setStatus("Новое CMC...");
                    } catch (MalformedURLException e1) {
                        logger.error(e1);
                    } catch (IOException e1) {
                        logger.error(e1);
                    }
                }
            });
        }
        return newSmsMenuItem;
    }

    /**
     * This method initializes saveContactMenuItem
     * 
     * @return javax.swing.JMenuItem
     */
    public JMenuItem getSaveContactMenuItem() {
        if (saveContactMenuItem == null) {
            saveContactMenuItem = new JMenuItem();
            saveContactMenuItem.setText("Сохранить контакт");
            saveContactMenuItem.setFont(new Font("UnDotum", Font.PLAIN, 12));
        }
        return saveContactMenuItem;
    }

    /**
     * This method initializes contactListMenuItem
     * 
     * @return javax.swing.JMenuItem
     */
    public JMenuItem getContactListMenuItem() {
        if (contactListMenuItem == null) {
            contactListMenuItem = new JMenuItem();
            contactListMenuItem.setText("Список контактов");
            contactListMenuItem.setFont(new Font("UnDotum", Font.PLAIN, 12));
        }
        return contactListMenuItem;
    }

    /**
     * This method initializes helpMenuItem
     * 
     * @return javax.swing.JMenuItem
     */
    private JMenuItem getHelpMenuItem() {
        if (helpMenuItem == null) {
            helpMenuItem = new JMenuItem();
            helpMenuItem.setText("Помощь");
            helpMenuItem.setFont(new Font("UnDotum", Font.PLAIN, 12));
        }
        return helpMenuItem;
    }

    /**
     * This method initializes aboutMenuItem
     * 
     * @return javax.swing.JMenuItem
     */
    public JMenuItem getAboutMenuItem() {
        if (aboutMenuItem == null) {
            aboutMenuItem = new JMenuItem();
            aboutMenuItem.setText("О программе");
            aboutMenuItem.setFont(new Font("UnDotum", Font.PLAIN, 12));
        }
        return aboutMenuItem;
    }

    
    public String getOperator() {
        return (String) operatorsComboBox.getSelectedItem(); 
    }
    
    public void setOperator(String operator) {
        operatorsComboBox.setSelectedItem(operator);
    }
    
    public String getPrefix() {
        return (String) prefixComboBox.getSelectedItem();
    }
    
    public void setPrefix(String prefix) {
        prefixComboBox.setSelectedItem(prefix);
    }
    
    public String getNumber() {
        return numberTextField.getText();
    }
    
    public void setNumber(String number) {
        numberTextField.setText(number);
    }
    
    public String getSender() {
        return senderTextField.getText();
    }
    
    public void setSender(String sender) {
        senderTextField.setText(sender);
    }
    
    public String getMessage() {
        return messageTextArea.getText();
    }
    
    public void setMessage(String message) {
        messageTextArea.setText(message);
    }
    
    public String getCaptchaCode() {
        return captchaCodeTextField.getText();
    }
    
    public void setCaptchaCode(String captchaCode) {
        captchaCodeTextField.setText(captchaCode);
    }
    
    public void setCaptchaImageLabel(String imageFileName) {
        captchaImageLabel.setIcon(new ImageIcon(imageFileName));
    }
    
    public boolean isTranslitUsed() {
        return translitCheckBox.isSelected();
    }
    
    public void setTranslitUsed(boolean flag) {
        translitCheckBox.setSelected(flag);
    }
    
    public void setStatus(String status) {
        statusBarLabel.setText(status);
    }
    
    private int getMessageLength(int maxMessageLength) {
        int length = 0;
        if (getSender() != null && getSender().trim().length() != 0) {
            length = Operator.FROM.length() + 1 + getSender().length();
        }
        return maxMessageLength - length - getMessage().length();
    }

 
}
